package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorService dishFlavorService;

    @Override
    @Transactional
    public void saveWithFlavors(DishDto dishDto) {
        //1. 向菜品表中添加一条数据，添加之前，dishDto是没有主键ID的，保存之后，id会自动赋值
        this.save(dishDto);
        //2. 向口味表中添加多条数据
        List<DishFlavor> flavors = dishDto.getFlavors();
        //TODO 给每一个DishFlavor设置dishId
        flavors.forEach(flavor -> flavor.setDishId(dishDto.getId()));
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public Page<DishDto> pageDishDto(Integer page, Integer pageSize, String name) {
        //1. 创建分页对象（封装页码，条数）
        Page<DishDto> pageInfo = new Page<>(page, pageSize);
        //2. 调用mapper去分页条件查询
        pageInfo = dishMapper.pageDishDto(pageInfo, name);
        //3. 返回pageInfo对象
        return pageInfo;
    }

    @Override
    public DishDto getByIdWithFlavors(Long id) {
        return dishMapper.getByIdWithFlavors(id);
    }

    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
        //1. 修改dish数据  update dish set xxx=xxx where id=?
        this.updateById(dishDto);
        //2. 修改dish_flavor数据  先删除，再添加    delete from dish_flavor where dish_id=?
        dishFlavorService.update().eq("dish_id", dishDto.getId()).remove();
        List<DishFlavor> flavors = dishDto.getFlavors();
        //TODO 设置dishId
        flavors.forEach(flavor -> flavor.setDishId(dishDto.getId()));
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public List<DishDto> listDishDto(Long categoryId, String name) {
        return dishMapper.listDishDto(categoryId, name);
    }

    @Override
    public List<DishDto> listDishDtoBySetmealId(Long setmealId) {
        return dishMapper.listDishDtoBySetmealId(setmealId);
    }
}


